import React, { useState, useEffect, useRef } from 'react';
import { TouchableHighlight, Modal, StyleSheet, TouchableOpacity, Text, Button, View, Image, ToastAndroid, ScrollView, Dimensions, Animated, PanResponder, Alert } from 'react-native';

import { Entypo } from '@expo/vector-icons';
import { Toast } from 'antd-mobile-rn';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from '../../api/axios'
import { useAuth, baseURL } from '../../context/AuthProvider';
import { useFocusEffect } from '@react-navigation/native';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} activeOpacity={0.9} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                padding: 2,
                ...style
            }

        }>
            <Text style={{ color: color }}>{children}</Text>
        </TouchableOpacity>
    )
}
const Buy = ({ navigation, route }) => {
    const [num, setNum] = useState(1)
    const [goods, setGoods] = useState();
    const [address, setAddress] = useState({})
    const [eff, setEff] = useState(0)
    const { user } = useAuth()
    // console.log(route.params);
    console.log(navigation.getState().routes[2].params);
    console.log(navigation.getState().routes[3].params);
    const commodityid = route.params.commodityid
    const subtract = () => {
        if (num != 1) {
            setNum(num - 1)
        }
    }
    const addNum = () => {
        if (num != 99) {
            setNum(num + 1)
        }
    }
    useFocusEffect(React.useCallback(() => {
        console.log('当前页面被激活啦!');
        console.log(12222222);
        console.log(commodityid);
        setEff(eff + 1)
        
        AsyncStorage.getItem('goodslist').then(
            data => {
                console.log(2222);
                // if(data){
                console.log(data);
                console.log((JSON.parse(data)).length);
                let newdata = JSON.parse(data);
                for (let i = 0; i < newdata.length; i++) {
                    if (newdata[i].commodityid == commodityid) {
                        // console.log(newdata[i]);
                        console.log(newdata[i].commodityid);
                        console.log(i);
                        setGoods(newdata[i])
                        console.log();
                        return
                    }
                }
                // } 
                console.log(5678);
            }
        )
        axios.post('/userreceive/getdefault', { userid: user.userid }).then(res => {
            console.log(res.data);
            setAddress(res.data[0])
        })
    }, []))
    const uploadlist = () => {
        if(address){
            axios.post('/order/upload', {commodityid: commodityid, addressid: address.addressid?address.addressid:'', comnum: num, userid: user.userid, com_price: goods.com_price, express_fee: goods.express_fee}).then(res=>{
                if (res.code == 200){
                    ToastAndroid.show("提交成功!", ToastAndroid.TOP); 
                    setTimeout(() => { navigation.navigate('Home') }, 1500)
                }
    
            })
        } else{
            alert('请选择地址')
        }
        
    }
    return (
        <View style={{ alignItems: 'center', justifyContent: 'space-between', height: '100%' }}>
            <View style={{ width: '100%', alignItems: 'center' }}>
                <View style={{ backgroundColor: '#fff', width: '95%', margin: 5, borderRadius: 10 }}>
                    <TouchableOpacity style={styles.miniCon} onPress={() => { setEff(eff + 1); navigation.navigate('address') }}>
                        <View>
                            <View style={{ width: '95%' }}><Text>{address?address.address:''}</Text></View>
                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <Text style={{ color: 'gray', fontSize: 13 }}>{address?address.name: '请添加地址'}</Text>
                                <Text>   </Text>
                                <Text style={{ color: 'gray', fontSize: 13 }}>{address?address.name:''}</Text>
                            </View>
                        </View>
                        <Entypo name="chevron-thin-right" size={14} color="black" />
                    </TouchableOpacity>
                </View>
                <View style={{ backgroundColor: '#fff', width: '95%', margin: 5 }}>
                    <View style={styles.miniCon} >
                        <View style={{ flexDirection: 'row', alignItems: 'center', width: '100%' }}>
                            <Image source={{ uri: goods ? baseURL+goods.first_img : '' }} style={{ height: 100, width: '20%', resizeMode: 'contain' }}></Image>
                            <View style={{ width: '80%', justifyContent: 'flex-end' }}>
                                <Text numberOfLines={1} style={{ width: '100%' }}>{goods ? goods.com_name : ''}</Text>
                                <Text>￥{goods ? goods.com_price : 0}</Text>
                                <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    <Btn style={{ borderWidth: 1, borderColor: 'gray', width: 20 }} onPress={subtract}>-</Btn>
                                    <Btn style={{ borderWidth: 1, borderColor: 'gray', width: 20 }}>{num}</Btn>
                                    <Btn style={{ borderWidth: 1, borderColor: 'gray', width: 20 }} onPress={addNum}>+</Btn>
                                </View>
                            </View>
                        </View>
                    </View>
                    <View style={styles.miniCon} >
                        <View style={{ flexDirection: 'row', alignItems: 'center', width: '100%', justifyContent: 'space-between' }}>
                            <Text style={{ color: 'gray' }}>配送服务</Text>
                            <View>
                                <Text style={{ justifyContent: 'flex-end' }}>快递 ￥{goods?goods.express_fee: 0}</Text>
                                <Text>付款后{goods ? goods.com_time : 48}小时内发货</Text>
                            </View>
                        </View>
                    </View>
                </View>
            </View>
            <View style={{ backgroundColor: '#fff', width: '100%', flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center' }}>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <Text style={{ color: 'gray', fontSize: 12, margin: 5 }}>共{num}件</Text>
                    <View style={{ flexDirection: 'row' }}>
                        <Text>合计:</Text>
                        <Text style={{ marginLeft: 1 }}>￥</Text>
                        <Text style={{ marginLeft: 1 }}>{goods ? goods.com_price * num + goods.express_fee : ''}</Text>
                    </View>
                </View>
                <Btn style={{ backgroundColor: '#9AD37A', padding: 5, borderRadius: 10, margin: 10 }} color='#fff'
                    onPress={uploadlist}> 提交订单 </Btn>
            </View>
        </View>
    )
}
const styles = StyleSheet.create({
    miniCon: {
        margin: '2%',
        alignItems: 'center',
        padding: '2%',
        justifyContent: 'space-between',
        flexDirection: 'row',
    },
    miniCon0: {
        margin: '2%',
        alignItems: 'center',
        padding: '2%'
    },
})
export default Buy